<template>
    <view class="volunteer-form-wrap">
        <!-- 拒绝原因提示 -->
        <view class="reject-notice" v-if="rejectReason">
            <view class="reject-title">申请被拒绝</view>
            <view class="reject-reason">{{ rejectReason }}</view>
        </view>

        <!-- 审核中提示 -->
        <view class="review-notice" v-if="auditStatus === 0">
            <view class="review-title">申请审核中</view>
            <view class="review-desc">您的志愿者申请正在审核中，请耐心等待</view>
        </view>

        <!-- 审核通过提示 -->
        <view class="approved-notice" v-if="auditStatus === 1">
            <view class="approved-title">申请已通过</view>
            <view class="approved-desc">恭喜您成为志愿者！以下是您的申请信息</view>
        </view>

        <view class="title">志愿者申请信息</view>

        <view class="form-box">
            <!-- 必填项 -->
            <view class="form-item">
                <view class="label required">姓名</view>
                <input class="input" v-model="formData.name" placeholder="请输入" @blur="validateField('name')" :disabled="isApproved || auditStatus === 0" />
            </view>

            <view class="form-item">
                <view class="label required">性别</view>
                <picker class="picker" :value="genderIndex" :range="genderOptions" @change="onGenderChange" :disabled="isApproved || auditStatus === 0">
                    <view class="picker-text" :data-placeholder="'请选择'">{{ getGenderText(formData.gender) || '' }}</view>
                </picker>
                <image src="../../static/right.png" mode="widthFix" class="right-icon" v-if="!isApproved && auditStatus !== 0"></image>
            </view>

            <view class="form-item">
                <view class="label required">所在区（市）</view>
                <picker class="picker" :value="addressIndex" :range="addressOptions" @change="onaddressChange" :disabled="isApproved || auditStatus === 0">
                    <view class="picker-text" :data-placeholder="'请选择'">{{ formData.address || '' }}</view>
                </picker>
                <image src="../../static/right.png" mode="widthFix" class="right-icon" v-if="!isApproved && auditStatus !== 0"></image>
            </view>

            <view class="form-item">
                <view class="label">民族</view>
                <picker class="picker" :value="nationalityIndex" :range="nationalityOptions" @change="onnationalityChange" :disabled="isApproved || auditStatus === 0">
                    <view class="picker-text" :data-placeholder="'请选择'">{{ formData.nationality || '' }}</view>
                </picker>
                <image src="../../static/right.png" mode="widthFix" class="right-icon" v-if="!isApproved && auditStatus !== 0"></image>
            </view>

            <view class="form-item">
                <view class="label">出生年月</view>
                <picker class="picker" mode="date" :value="formData.birthday" @change="onbirthdayChange" :disabled="isApproved || auditStatus === 0">
                    <view class="picker-text" :data-placeholder="'年/月/日'">{{ formData.birthday || '' }}</view>
                </picker>
                <image src="../../static/right.png" mode="widthFix" class="right-icon" v-if="!isApproved && auditStatus !== 0"></image>
            </view>

            <view class="form-item">
                <view class="label required">身份证号</view>
                <input class="input" v-model="formData.idno" placeholder="请输入" @blur="validateField('idno')" :disabled="isApproved || auditStatus === 0" />
            </view>

            <view class="form-item">
                <view class="label required">电话号码</view>
                <input class="input" v-model="formData.phone" placeholder="请输入" type="number"
                    @blur="validateField('phone')" :disabled="isApproved || auditStatus === 0" />
            </view>

            <view class="form-item">
                <view class="label">职业</view>
                <input class="input" v-model="formData.career" placeholder="请输入" :disabled="isApproved || auditStatus === 0" />
            </view>

            <!-- 志愿服务领域复选框 -->
            <view class="form-item checkbox-item">
                <view class="label required">意愿志愿服务领域</view>
                <view class="checkbox-container">
                    <view 
                        v-for="(field, index) in volunteerFieldOptions" 
                        :key="index"
                        class="checkbox-item"
                        :class="{ 'checked': formData.realm.includes(field) }"
                        @click="toggleVolunteerField(field)"
                        :style="{ opacity: (isApproved || auditStatus === 0) ? 0.6 : 1 }"
                    >
                        <view class="checkbox-icon">{{ formData.realm.includes(field) ? '✓' : '' }}</view>
                        <text class="checkbox-text">{{ field }}</text>
                    </view>
                </view>
                <view class="checkbox-tip">最多选择4项</view>
            </view>
        </view>


        <view class="footer-btn">
            <view class="primary-btn" @click="submitForm" v-if="!isApproved && auditStatus !== 0">提交申请</view>
            <view class="review-btn" v-if="auditStatus === 0">审核中</view>
            <view class="approved-btn" v-if="auditStatus === 1">已是志愿者</view>
        </view>
    </view>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import {
    validateRequired,
    validatePhoneWithError,
    validateIdCardWithError,
    validateDate,
    validateSelect,
    validateCheckbox
} from '@/utils/validation.js'
import { submitVolunteerApplication, uploadFile, getVolunteerInfo } from '@/utils/api.js'
import config from '@/config/index.js'

// 表单数据
const formData = reactive({
    name: '',
    gender: '',
    address: '',
    nationality: '',
    birthday: '',
    idno: '',
    phone: '',
    career: '',
    realm: [],
})

// 错误信息
const errors = reactive({
    name: '',
    gender: '',
    address: '',
    nationality: '',
    birthday: '',
    idno: '',
    phone: '',
    realm: '',
})

// 选择器索引
const genderIndex = ref(-1)
const addressIndex = ref(-1)
const nationalityIndex = ref(-1)

// 签名相关
const isCanvas = ref(false)

// 状态相关
const isApproved = ref(false)
const rejectReason = ref('')
const auditStatus = ref(null)

// 选项数据（从配置文件获取）
const genderOptions = config.form.genderText
const addressOptions = config.form.addresss
const nationalityOptions = config.form.nationalitys
const volunteerFieldOptions = config.form.volunteerFields

// 获取性别显示文本
const getGenderText = (genderValue) => {
    if (!genderValue) return ''
    const index = config.form.gender.indexOf(String(genderValue))
    return index !== -1 ? config.form.genderText[index] : ''
}

// 选择器事件处理
const onGenderChange = (e) => {
    if (isApproved.value || auditStatus.value === 0) return
    genderIndex.value = e.detail.value
    formData.gender = config.form.gender[e.detail.value] // 存储数字值
    validateField('gender')
}

const onaddressChange = (e) => {
    if (isApproved.value || auditStatus.value === 0) return
    addressIndex.value = e.detail.value
    formData.address = addressOptions[e.detail.value]
    validateField('address')
}

const onnationalityChange = (e) => {
    if (isApproved.value || auditStatus.value === 0) return
    nationalityIndex.value = e.detail.value
    formData.nationality = nationalityOptions[e.detail.value]
}

const onbirthdayChange = (e) => {
    if (isApproved.value || auditStatus.value === 0) return
    formData.birthday = e.detail.value
}

// 切换志愿服务领域选择
const toggleVolunteerField = (field) => {
    if (isApproved.value || auditStatus.value === 0) return
    const index = formData.realm.indexOf(field)
    if (index > -1) {
        formData.realm.splice(index, 1)
    } else {
        if (formData.realm.length < 4) {
            formData.realm.push(field)
        } else {
            uni.showToast({
                title: '最多只能选择4项',
                icon: 'none'
            })
        }
    }
    validateField('realm')
}


// 字段验证
const validateField = (field) => {
    errors[field] = ''

    switch (field) {
        case 'name':
            errors.name = validateRequired(formData.name, '姓名')
            break
        case 'gender':
            errors.gender = validateSelect(formData.gender, '性别')
            break
        case 'address':
            errors.address = validateSelect(formData.address, '所在区（市）')
            break
        case 'idno':
            errors.idno = validateIdCardWithError(formData.idno, '身份证号')
            break
        case 'phone':
            errors.phone = validatePhoneWithError(formData.phone, '电话号码')
            break
        case 'realm':
            errors.realm = validateCheckbox(formData.realm, '意愿志愿服务领域', 4)
            break
    }
}

// 获取志愿者状态和详情
const getVolunteerDetail = async () => {
    try {
        const result = await getVolunteerInfo()
        console.log('志愿者信息API返回:', result)
        if (result.code === 0 && result.data) {
            const volunteerInfo = result.data
            auditStatus.value = volunteerInfo.auditStatus
            
            if (volunteerInfo.auditStatus == 1) {
                // 审核通过
                isApproved.value = true
                // 回显数据
                fillVolunteerFormData(volunteerInfo)
            } else if (volunteerInfo.auditStatus == 2) {
                // 被拒绝
                rejectReason.value = volunteerInfo.reason || '申请被拒绝'
                // 回显之前的数据
                fillVolunteerFormData(volunteerInfo)
            } else if (volunteerInfo.auditStatus == 0) {
                // 审核中
                uni.showToast({
                    title: '您的申请正在审核中',
                    icon: 'none'
                })
                // 回显数据但不允许编辑
                fillVolunteerFormData(volunteerInfo)
            }
        }
    } catch (error) {
        console.error('获取志愿者详情失败:', error)
        uni.showToast({
            title: '获取信息失败',
            icon: 'none'
        })
    }
}

// 回显志愿者表单数据
const fillVolunteerFormData = (data) => {
    console.log('回显志愿者数据:', data)
    
    // 基本信息
    formData.name = data.name || ''
    formData.gender = data.gender || ''
    formData.address = data.address || ''
    formData.nationality = data.nationality || ''
    formData.birthday = data.birthday || ''
    formData.idno = data.idno || ''
    formData.phone = data.phone || ''
    formData.career = data.career || ''
    formData.realm = data.realm || []
    
    // 设置选择器索引
    setPickerIndexes()
}

// 设置选择器索引
const setPickerIndexes = () => {
    if (formData.gender) {
        // 根据数字值找到对应的索引，将数字转换为字符串进行比较
        const genderValueIndex = config.form.gender.indexOf(String(formData.gender))
        if (genderValueIndex !== -1) {
            genderIndex.value = genderValueIndex
        }
        console.log('志愿者性别索引设置:', genderValueIndex, '性别值:', formData.gender)
    }
    if (formData.address) {
        addressIndex.value = addressOptions.indexOf(formData.address)
        console.log('志愿者地址索引设置:', addressIndex.value, '地址值:', formData.address)
    }
    if (formData.nationality) {
        nationalityIndex.value = nationalityOptions.indexOf(formData.nationality)
        console.log('志愿者民族索引设置:', nationalityIndex.value, '民族值:', formData.nationality)
    }
}

// 表单提交
const submitForm = async () => {
    // 验证所有必填字段
    const requiredFields = ['name', 'gender', 'address', 'idno', 'phone', 'realm']
    let isValid = true

    requiredFields.forEach(field => {
        validateField(field)
        if (errors[field]) {
            isValid = false
        }
    })

    if (!isValid) {
        uni.showToast({
            title: '请完善必填信息',
            icon: 'none'
        })
        return
    }

    // 显示加载提示
    uni.showLoading({
        title: '提交中...'
    })

    try {

        // 准备提交数据
        const submitData = {
            ...formData,
        }

        // 提交表单
        const result = await submitVolunteerApplication(submitData)

        uni.hideLoading()

        if (result.code === 0) {
            uni.showToast({
                title: '申请提交成功',
                icon: 'success'
            })

            // 重新获取志愿者状态
            await getVolunteerDetail()

            // 延迟跳转回首页
            setTimeout(() => {
                uni.navigateBack()
            }, 1500)
        } else {
            uni.showToast({
                title: result.message || '提交失败',
                icon: 'none'
            })
        }
    } catch (error) {
        uni.hideLoading()
        console.error('提交失败:', error)
        uni.showToast({
            title: '网络错误，请重试',
            icon: 'none'
        })
    }
}

// 页面加载时获取状态
onMounted(() => {
    getVolunteerDetail()
})
</script>

<style lang="scss" scoped>
.volunteer-form-wrap {
    padding: 24rpx;
    background: #f5f5f5;
    padding-bottom: 200rpx; /* 为固定底部按钮留出空间 */

    .reject-notice {
        background: #fff3cd;
        border: 1px solid #ffeaa7;
        border-radius: 8rpx;
        padding: 16rpx;
        margin-bottom: 24rpx;

        .reject-title {
            font-size: 28rpx;
            color: #856404;
            font-weight: bold;
            margin-bottom: 8rpx;
        }

        .reject-reason {
            font-size: 26rpx;
            color: #856404;
            line-height: 1.4;
        }
    }

    .review-notice {
        background: #fff3cd;
        border: 1px solid #ffeaa7;
        border-radius: 8rpx;
        padding: 16rpx;
        margin-bottom: 24rpx;

        .review-title {
            font-size: 28rpx;
            color: #856404;
            font-weight: bold;
            margin-bottom: 8rpx;
        }

        .review-desc {
            font-size: 26rpx;
            color: #856404;
            line-height: 1.4;
        }
    }

    .approved-notice {
        background: #d4edda;
        border: 1px solid #c3e6cb;
        border-radius: 8rpx;
        padding: 16rpx;
        margin-bottom: 24rpx;

        .approved-title {
            font-size: 28rpx;
            color: #155724;
            font-weight: bold;
            margin-bottom: 8rpx;
        }

        .approved-desc {
            font-size: 26rpx;
            color: #155724;
            line-height: 1.4;
        }
    }

    .title {
        font-size: 32rpx;
        font-weight: 600;
        line-height: 52rpx;
        color: #000;
        padding: 20rpx 10rpx;
    }

    .form-box,
    .signature-box {
        background: #FFFFFF;
        border-radius: 16rpx;
        padding: 0 24rpx;
        border: 2rpx solid #E7E8EB;

        .form-item {
            min-height: 84rpx;
            display: flex;
            align-items: center;
            justify-content: space-between;
            border-bottom: 2rpx solid #F6F6F6;
            padding: 16rpx 0;

            &:last-child {
                border-bottom: none;
            }

            &.checkbox-item {
                flex-direction: column;
                align-items: flex-start;
                padding: 24rpx 0;

                .label {
                    margin-bottom: 16rpx;
                }

                .checkbox-container {
                    width: 100%;
                    display: flex;
                    flex-wrap: wrap;
                    gap: 16rpx;
                }

                .checkbox-item {
                    display: flex;
                    align-items: center;
                    padding: 12rpx 16rpx;
                    border: 2rpx solid #e0e0e0;
                    border-radius: 8rpx;
                    background: #fff;
                    min-width: 160rpx;
                    justify-content: center;

                    &.checked {
                        border-color: #007aff;
                        background: #f0f8ff;
                    }

                    .checkbox-icon {
                        width: 32rpx;
                        height: 32rpx;
                        border: 2rpx solid #ccc;
                        border-radius: 4rpx;
                        display: flex;
                        align-items: center;
                        justify-content: center;
                        margin-right: 8rpx;
                        font-size: 20rpx;
                        color: #007aff;
                        background: #fff;

                        &:empty {
                            background: #fff;
                        }
                    }

                    .checkbox-text {
                        font-size: 26rpx;
                        color: #333;
                    }
                }

                .checkbox-tip {
                    font-size: 24rpx;
                    color: #999;
                    margin-top: 12rpx;
                }
            }

            .label {
                font-size: 28rpx;
                color: rgba(0, 0, 0, 0.60);
                font-weight: 500;
                min-width: 160rpx;

                &.required::after {
                    content: '*';
                    color: #ff4757;
                    margin-left: 4rpx;
                }
            }

            .input {
                flex: 1;
                font-size: 28rpx;
                height: 84rpx;
                padding: 0 16rpx;
                background: #ffffff;
                text-align: right;

                &::placeholder {
                    color: rgba(0, 0, 0, 0.3);
                }

                &:disabled {
                    background: #f8f8f8;
                    color: #666;
                }
            }

            .picker {
                flex: 1;
                height: 84rpx;
                padding: 0 16rpx;

                .picker-text {
                    height: 84rpx;
                    line-height: 84rpx;
                    font-size: 28rpx;
                    color: #333;
                    text-align: right;

                    &:empty {
                        color: rgba(0, 0, 0, 0.3);
                    }

                    &:empty::before {
                        content: attr(data-placeholder);
                    }
                }

                &:disabled {
                    .picker-text {
                        background: #f8f8f8;
                        color: #666;
                    }
                }
            }

            .right-icon {
                width: 24rpx;
                height: 24rpx;
                flex-shrink: 0;
                margin-left: 8rpx;
            }
        }
    }

    .signature-box {
        background: #FFFFFF;
        border-radius: 16rpx;
        padding: 24rpx;

        .desc {
            font-size: 26rpx;
            color: rgba(0, 0, 0, 0.40);
            line-height: 44rpx;
            margin-bottom: 24rpx;
            text-align: justify;
            text-indent: 2em;
        }
    }

    .sign-title {
        padding-top: 0;
        padding-left: 0;
    }

    .sign-box {
        margin-bottom: 24rpx;

        .sign-placeholder {
            height: 300rpx;
            background: #f8f8f8;
            border: 2rpx dashed #BBBCBE;
            border-radius: 16rpx;
            display: flex;
            align-items: center;
            justify-content: center;
            color: #999;
            font-size: 28rpx;
        }

        .signature-preview {
            width: 100%;
            height: 200rpx;
            border-radius: 8rpx;
            border: 2rpx solid #e0e0e0;
        }
    }

    .sign-btn-box {
        display: flex;
        align-items: center;
        justify-content: flex-end;
        gap: 16rpx;
    }

    .sign-btn {
        width: 112rpx;
        height: 44rpx;
        border: 2rpx solid #FA7A53;
        color: #FA7A53;
        border-radius: 8rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 28rpx;
    }

    .reset-btn {
        width: 112rpx;
        height: 44rpx;
        background: #f5f5f5;
        color: #666;
        border-radius: 8rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 28rpx;
    }
}

.footer-btn {
    position: fixed;
    bottom: 0;
    left: 0;
    width: calc(100% - 48rpx);
    height: 100rpx;
    background: #fff;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 24rpx 24rpx 28rpx 24rpx;
    z-index: 100;

    .primary-btn {
        width: 100%;
        height: 88rpx;
        background: #F9623E;
        color: #fff;
        border-radius: 44rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 32rpx;
        font-weight: 500;
    }

    .review-btn {
        width: 100%;
        height: 88rpx;
        background: #999;
        color: #fff;
        border-radius: 44rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 32rpx;
        font-weight: 500;
    }

    .approved-btn {
        width: 100%;
        height: 88rpx;
        background: #999;
        color: #fff;
        border-radius: 44rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 32rpx;
        font-weight: 500;
    }
}
</style>